let utils = require('../../utils/util.js');
let app = getApp()
Page({

  /*页面的初始数据*/
  data: {
    show: '',
    dataList: '', //总订单数据
    dataList2: '', //门票订单数据
    coupon_type: '', //优惠券类型
    discount: 0, //折率
    hiddenmodalput: true, //可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
    coupon_id: '', //优惠券id
    pwd: '', //支付密码
    tapIndex: '', //支付方式
    now_date: '',
    date: '',
    hidden: true,
    length: '', // 囤票个数
    hoardings: {}, // 囤票 数据
    drop: true,
    sort: 1, // 1 优惠卷 2囤卷
    money: '0.00',
  },
  /* 生命周期函数--监听页面加载*/
  onLoad: function(options) {
    let that = this;
    let date2 = new Date();
    that.setData({
      date: utils.formatTime(date2),
      now_date: utils.formatTime(date2),
      now_times: utils.formatTimes(date2),
      hidden: false
    })
    that.checkHoarding() // 判断是否参见囤票活动
    wx.request({
      url: app.data.url + '/is_instore', // 判断有没有计时
      header: app.getHeader(),
      success: function(res) {
        if (res.data.type == 0) {
          wx.request({
            url: app.data.url + '/first_date',
            header: app.getHeader(),
            success: function(res) {
              that.setData({
                start_date: res.data.substr(0, 10),
              })
              wx.request({
                url: app.data.url + '/choose_date_order',
                header: app.getHeader(),
                method: "POST",
                data: {
                  date: utils.formatTime(date2)
                },
                success: function(res) {
                  for (let i in res.data.order_day) {
                    switch (res.data.order_day[i].pay_way) {
                      case 1:
                        res.data.order_day[i].pay_type = '微信支付';
                        break;
                      case 2:
                        res.data.order_day[i].pay_type = '余额支付';
                        break;
                      case 3:
                        res.data.order_day[i].pay_type = '企业支付';
                        break;
                      case 4:
                        res.data.order_day[i].pay_type = '企业支付';
                        break;
                    }
                  }
                  that.setData({
                    dataList: res.data,
                    show: false,
                    hidden: true
                  })
                }
              })
            }
          })
        } else {
          wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#1d212b'
          })
          wx.request({
            url: app.data.url + '/buy_ticket',
            header: app.getHeader(),
            success: function(res) {

              if (res.data.oncustomer.coupon.length > 0) {

                if (that.data.length > 0) {

                  that.setData({
                    sort: 2,
                  })

                }
                const datall = res.data.oncustomer.coupon[0]
                that.setData({
                  dataList2: res.data,
                  show: true,
                  coupon_type: datall.types[0].name, //优惠券类型
                  discount: datall.ratio, //折率
                  coupon_id: datall.id,
                  money: res.data.ticket.price
                })
                that.money()

              } else {
                if (that.data.length > 0) {
                  that.setData({
                    show: true,
                    dataList2: res.data,
                    sort: 2
                  })
                } else {
                  that.setData({
                    show: true,
                    dataList2: res.data
                  })
                }
                that.money()
              }
              that.inside()
            }
          })
          wx.hideNavigationBarLoading()
        }
      },
    })
  },
  money: function() {
    var that = this
    wx.request({ // 余额
      url: app.data.url + '/diposit_show',
      header: app.getHeader(),
      success: function(res) {
        var money = 0
        var yuProice = res.data.card_money
        if (that.data.dataList2.oncustomer.coupon.length > 0) { // 优惠卷
          let truePrice = that.data.dataList2.ticket.price
          money = truePrice * (that.data.discount / 10)
          that.setData({
            money: money
          })
        } else {

          if (that.data.length > 0) {
            that.setData({
              money: money
            })
          } else {
            that.setData({
              money: that.data.dataList2.ticket.price
            })
          }
        }
      }
    })
  },
  // 下拉框
  drop: function() {
    this.setData({
      drop: !this.data.drop
    })
  },
  hide: function() {
    this.setData({
      drop: !this.data.drop
    })
  },
  bind1: function(e) {
    var that = this;
    that.setData({
      sort: e.currentTarget.dataset.sort,
      drop: !this.data.drop
    })
    that.money()
  },
  bind2: function(e) {
    var that = this;
    that.setData({
      money: 0,
      sort: 2,
      drop: !this.data.drop
    })
    that.setData({

    })
  },
  inside: function() {
    var that = this;
    wx.request({ // 检验是否员工
      url: app.data.url + '/isStaff',
      header: app.getHeader(),
      method: 'post',
      success: function(res) {
        if (res.data.tips == 200) { // tips  200 员工 204 非员工
          that.setData({
            show: true,
            sort: 0
          })
        }
      }
    })
  },
  select_coupon: function() { // 选择优惠价列表
    var that = this;
    var types = that.data.dataList2.oncustomer.coupon;
    if (types.length == 0) {
      return false
    } else {
      wx.navigateTo({
        url: '../coupon/coupon?caozuo=select',
      })
    }
  },
  select_writ: function() { // 选择囤票列表
    var that = this;
    if (that.data.length == 0) {
      return false
    } else {
      wx.navigateTo({
        url: '../coupon/writ?caozuo=select',
      })
    }
  },
  // 支付方式
  payment: function() {
    var that = this;
    wx.request({ // 余额
      url: app.data.url + '/diposit_show',
      header: app.getHeader(),
      success: function(res) {
        var money = that.data.dataList2.ticket.price
        var yuProice = res.data.card_money
        if (that.data.dataList2.oncustomer.coupon.length > 0) { // 优惠卷
          let truePrice = that.data.dataList2.ticket.price
          money = truePrice * (that.data.discount / 10)
          that.setData({
            money: money
          })
        }
        if (yuProice >= money) { // 判断余额大于等于支付金额
          that.requestPayNoPass(money, 2); // 免密查询
        } else {
          if (app.data.passSet && app.data.hasRenzheng) {
            that.showAction(['微信支付', '余额支付', '企业支付'])
          } else if (app.data.passSet) {
            that.showAction(['微信支付', '余额支付'])
          } else if (app.data.hasRenzheng) {
            that.showAction(['微信支付', '企业支付'])
          } else {
            that.showAction(['微信支付'])
          }
        }
      }
    })
  },
  showAction(flag) { // 门票不足买门票
    var that = this;
    wx.showActionSheet({
      itemList: flag,
      success: function(res) {
        if (res.tapIndex == 1 || res.tapIndex == 2 || res.tapIndex == 3) {
          let truePrice = that.data.dataList2.ticket.price
          let money = truePrice - truePrice * (that.data.discount / 10)
          that.requestPayNoPass(money, res.tapIndex + 1);
          // wx.request({
          //   url: app.data.url + '/noPasswordPay',
          //   method: "POST",
          //   data: {
          //     money: truePrice - truePrice * (that.data.discount / 10)
          //   },
          //   header: app.getHeader(),
          //   success: function (ress) {
          //     if (ress.data.tips == 200) {
          //       //on
          //       that.setData({
          //         tapIndex: res.tapIndex + 1
          //       })
          //       that.payPro(true)
          //     } else {
          //       //off
          //       that.setData({
          //         hiddenmodalput: false,
          //         tapIndex: res.tapIndex + 1
          //       })
          //     }
          //   }
          // })
        } else {
          wx.request({ //买门票操作
            url: app.data.url + '/ticket_order',
            method: 'POST',
            header: app.getHeader(),
            data: {
              type: 1,
              coupon_id: that.data.coupon_id,
              ticket_id: that.data.dataList2.ticket.id,
            },
            success: function(res) {
              var order = res.data;
              console.log("优惠卷id", that.data.coupon_id)

              wx.requestPayment({
                'timeStamp': order.timeStamp,
                'nonceStr': order.nonceStr,
                'package': order.package,
                'signType': order.signType,
                'paySign': order.paySign,
                success: function(res) {
                  console.log("微信支付",res)

                  if (that.data.coupon_id > 0) {
                    console.log("没有优惠卷")
                    wx.request({
                      url: app.data.url + '/reduceCoupon',
                      header: app.getHeader(),
                      method: 'post',
                      data: {
                        coupon_id: that.data.coupon_id
                      },
                      success: function(res) {
                        console.log(res)
                      }
                    })
                  }
                  wx.request({
                    url: app.data.url + '/openlock',
                    header: app.getHeader(),
                    method: 'GET',
                    success: function(res) {
                      wx.showToast({
                        title: "购买成功!",
                        duration: 500,
                      });
                      app.data.out = 'jin'
                      wx.redirectTo({
                        url: '../progress/progress?out=jin'
                      })
                    },
                    fail: function(res) {
                      wx.showModal({
                        title: '提示',
                        content: '支付失败！',
                        showCancel: false
                      })

                    },
                    complete: function(res) {},
                  })

                },
                fail: function(res) {}
              })
            },
          })
        }
      },
      fail: function(res) {}
    })
  },
  requestPayNoPass(money, indexs) {
    const that = this
    wx.request({
      url: app.data.url + '/noPasswordPay', //检验是否满足免密支付
      method: "POST",
      data: {
        money: money
      },
      header: app.getHeader(),
      success: function(ress) {

        if (ress.data.tips == 200) {
          //on 满足免密支付
          that.setData({
            tapIndex: indexs
          })
          if (that.data.sort == 1) { // 优惠卷
            that.payPro(true)
          } else { // 囤票
            that.payPro1()
          }
        } else {
          //off 不满足免密支付
          that.setData({
            hiddenmodalput: false,
            tapIndex: indexs
          })
        }
      }
    })
  },
  payPro(mian) { // 优惠卷
    var that = this;
    if (!mian) { // 密码支付
      var pwd = that.data.pwd;
      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(pwd)) {
        wx.showModal({
          title: '提示',
          content: '密码不正确，请重新输入！',
          showCancel: false
        })
        that.setData({
          pwd: ''
        })
        return false
      }
      var param = {
        type: that.data.tapIndex,
        coupon_id: that.data.coupon_id,
        ticket_id: that.data.dataList2.ticket.id,
        password: that.data.pwd
      }
    } else {
      // 免密支付
      var param = {
        type: that.data.tapIndex,
        coupon_id: that.data.coupon_id,
        ticket_id: that.data.dataList2.ticket.id,
      }
    }
    this.setData({
      hiddenmodalput: true
    })
    wx.showLoading({
      title: '正在支付...',
    })
    wx.request({ // 优惠卷支付
      url: app.data.url + '/ticket_order',
      method: "POST",
      header: app.getHeader(),
      data: param,
      success: function(res) {
        wx.hideLoading()
        if (res.data.tips == 1) { //成功
          wx.showNavigationBarLoading()


          wx.request({
            url: app.data.url + '/openlock',
            header: app.getHeader(),
            method: 'POST',
            success: function(ress) {
              wx.showToast({
                title: "购买成功!",
                duration: 100,
                success: function() {
                  wx.showNavigationBarLoading()
                  app.data.out = 'jin'
                  wx.redirectTo({
                    url: '../progress/progress?out=jin'
                  })
                }
              });
            },
            fail: function(ress) {},
            complete: function(ress) {},
          })


        } else if (res.data.tips == 10) {

          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 11) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '密码错误！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 12) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '余额不足！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        }
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '支付失败！',
          showCancel: false
        })
        that.setData({
          pwd: ''
        })
      }
    })
  },
  payPro1() { // 囤票支付
    var that = this;
    wx.showLoading({
      title: '正在支付...',
    })
    wx.request({
      url: app.data.url + '/ticket_order', // 囤票支付
      method: "POST",
      header: app.getHeader(),
      data: {
        type: 5,
        ticket_id: that.data.dataList2.ticket.id,
        hoarding_ticket_id: that.data.hoardings.hoarding_ticket_id
      },
      success: function(res) {
        wx.hideLoading()
        if (res.data.tips == 1) { //成功
          wx.showNavigationBarLoading()
          wx.request({
            url: app.data.url + '/openlock',
            header: app.getHeader(),
            method: 'POST',
            success: function(ress) {
              wx.showToast({
                title: "购买成功!",
                duration: 100,
                success: function() {
                  wx.showNavigationBarLoading()
                  app.data.out = 'jin'
                  wx.redirectTo({
                    url: '../progress/progress?out=jin'
                  })
                }
              });
            },
            fail: function(ress) {},
            complete: function(ress) {},
          })

        } else if (res.data.tips == 10) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 11) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '密码错误！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 12) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '余额不足！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        }
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '支付失败！',
          showCancel: false
        })
        that.setData({
          pwd: ''
        })
      }
    })
  },
  payPro2() { // 员工支付
    var that = this;
    wx.showLoading({
      title: '正在支付...',
    })
    wx.request({
      url: app.data.url + '/ticket_order', // 囤票支付
      method: "POST",
      header: app.getHeader(),
      data: {
        ticket_id: that.data.dataList2.ticket.id
      },
      success: function(res) {
        wx.hideLoading()
        if (res.data.tips == 1) { //成功
          wx.showNavigationBarLoading()

          wx.request({
            url: app.data.url + '/openlock',
            header: app.getHeader(),
            method: 'POST',
            success: function(ress) {
              wx.showToast({
                title: "购买成功!",
                duration: 100,
                success: function() {
                  wx.showNavigationBarLoading()
                  app.data.out = 'jin'
                  wx.redirectTo({
                    url: '../progress/progress?out=jin'
                  })
                }
              });
            },
            fail: function(ress) {},
            complete: function(ress) {},
          })

        } else if (res.data.tips == 10) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 11) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '密码错误！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        } else if (res.data.tips == 12) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '余额不足！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.payment()
              }
            }
          })
          that.setData({
            pwd: ''
          })
        }
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '支付失败！',
          showCancel: false
        })
        that.setData({
          pwd: ''
        })
      }
    })
  },

  change: function(e) {
    var that = this;
    var pwd = e.detail.value;
    that.setData({
      pwd: pwd
    })
  },
  //点击按钮痰喘指定的hiddenmodalput弹出框  
  modalinput: function() {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按钮  
  cancel: function() {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function() {
    var that = this;
    if (that.data.sort == 1) { // 优惠卷
      that.payPro()
    } else { // 囤票
      that.payPro1()
    }
  },

  bindViewEvent: function(e) { // 用户选择日期  
    var that = this;
    var date = e.detail.value
    that.setData({
      now_date: date
    })
    wx.request({
      url: app.data.url + '/choose_date_order',
      header: app.getHeader(),
      method: "POST",
      data: {
        date: date
      },
      success: function(res) {
        for (let i in res.data.order_day) {
          switch (res.data.order_day[i].pay_way) {
            case 1:
              res.data.order_day[i].pay_type = '微信支付';
              break;
            case 2:
              res.data.order_day[i].pay_type = '余额支付';
              break;
            case 3:
              res.data.order_day[i].pay_type = '企业支付';
              break;
            case 4:
              res.data.order_day[i].pay_type = '企业支付';
              break;
          }
        }
        that.setData({
          dataList: res.data
        })
      }
    })

  },
  onReady: function() {},
  checkHoarding: function() { // 判断用户是否参加了囤票活动
    var that = this
    wx.request({
      url: app.data.url + '/checkHoarding',
      header: app.getHeader(),
      method: 'post',
      success: function(res) {
        if (res.data.tips == 200) {
          that.setData({
            hoardings: res.data.myHoardingArr[0],
            length: res.data.myHoardingArr.length
          })
        } else {
          // wx.showToast({
          //   title: res.data.msg,
          //   icon: 'none'
          // })
        }
      },
    })
  },
  /* 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})